package com.dingding.common.core.upload;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.log4j.Logger;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.dingding.common.core.config.ImageUploadConfig;
import com.dingding.common.core.util.ToolUtil;

/**
 * 
 * @ClassName: UploadUtil
 * @Description: 图片上传
 * @author cheshaowei
 * @date 2015-11-16 下午05:42:47
 */
public class UploadUtil {

	private static final Logger log = Logger.getLogger(UploadUtil.class);

	private static OSSClient client = null;

	static {
		// 初始化OSSCLient
		client = new OSSClient(ImageUploadConfig.getIMAGE_UPLOAD_PATH(), ImageUploadConfig.getIMAGE_UPLOAD_ACCESSID(),
				ImageUploadConfig.getIMAGE_UPLOAD_ACCESS_SECRET());
	}

	/**
	 * @Title: uploadImageToOss
	 * @Description:上传图片到OSS服务器
	 * @param uploadData 待上传的图片数据   
	 * @param imageName 图片名称
	 * @author cheshaowei
	 * @throws
	 */
	public boolean uploadImageToOss(byte[] uploadImageData, String imageName) {

		InputStream content = null;

		try {
			// 获取指定文件的输入流
			content = new ByteArrayInputStream(uploadImageData);
			// 创建上传Object的Metadata
			ObjectMetadata meta = new ObjectMetadata();
			// 必须设置ContentLength
			meta.setContentLength(content.available());
			// 设置上传格式
			meta.setContentType("image/jpeg");
			// 不使用缓存
			meta.setCacheControl("no-cache");
			// 上传Object
			PutObjectResult result = client.putObject(ImageUploadConfig.getSTORE_BUCKETNAME(), imageName, content,
					meta);
			// 上传图片失败
			if (result != null && ToolUtil.isBlank(result.getETag())) {
				return false;
			} else {
				return true;
			}
		} catch (IOException e) {
			log.error("上传图片出现异常！");
			return false;
		} finally {
			if (content != null) {
				try {
					content.close();
				} catch (IOException e) {
					log.error("关闭输入流出现异常！", e);
				}
			}
		}
	}

	/**
	 *
	 * @Title: deleteImage 
	 * @Description:删除图片对象
	 * @param name 要删除的图片对象名称
	 * @author cheshaowei
	 * @throws
	 */
	public void deleteImage(String imgeName) {

		client.deleteObject(ImageUploadConfig.getSTORE_BUCKETNAME(), imgeName);

	}

}
